import matplotlib.pyplot as plt
import numpy as np

# 设置中文字体和负号显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 数据
years = ["2017", "2018", "2019", "2020", "2021", "2022"]
sales = [1603, 2106, 2406, 3265, 3721, 3921]
growth_rate = [27, 31, 14, 36, 14, 5]

# 将年份转换为数字
x = np.arange(len(years))

# 创建图表和子图
fig, ax1 = plt.subplots()

# 设置背景颜色
fig.patch.set_facecolor('#1A1E43')
ax1.set_facecolor('#1A1E43')
ax2 = ax1.twinx()
ax2.set_facecolor('#1A1E43')

# 绘制柱状图
bar_width = 0.35
bars = ax1.bar(x, sales, bar_width, label='销售量', color='#4E79A7')

# 设置x轴和y轴
ax1.set_xlabel('年份', color='white')
ax1.set_ylabel('销售量', color='#4E79A7')
ax1.set_xticks(x)
ax1.set_xticklabels(years)
ax1.tick_params(axis='y', labelcolor='#4E79A7')

# 在柱状图上方添加文本标签
for bar in bars:
    height = bar.get_height()
    ax1.annotate('{}'.format(height),
                 xy=(bar.get_x() + bar.get_width() / 2, height),
                 xytext=(0, 3),  # 3 points vertical offset
                 textcoords="offset points",
                 ha='center', va='bottom', color='white')

# 创建第二个y轴，用于显示同比增长率
ax2.set_ylabel('同比增长率 (%)', color='#E15759')
ax2.plot(x, growth_rate, label='同比', color='#E15759', marker='o')
ax2.tick_params(axis='y', labelcolor='#E15759')

# 在折线图上方添加文本标签
for i, txt in enumerate(growth_rate):
    ax2.annotate('{}%'.format(txt), (x[i], growth_rate[i]), textcoords="offset points", xytext=(0, 10), ha='center',
                 color='#E15759')

fig.tight_layout()
fig.subplots_adjust(top=0.8)
# 添加标题
# 添加子标题
plt.text(0.45, 1.1, '平台销量近6年持续增长，但近两年增长率有所放缓', ha='center', va='center',
         transform=plt.gca().transAxes, fontsize=15, color='white')
plt.text(0.2, 1.2, '近六年销售量及增长率', ha='center', va='center',
         transform=plt.gca().transAxes, fontsize=15, color='white')

# 隐藏坐标轴和边框
ax1.axis('off')
ax1.spines[['top', 'right', 'bottom', 'left']].set_visible(False)
ax2.axis('off')
ax2.spines[['top', 'right', 'bottom', 'left']].set_visible(False)

# 显示图例, 设置图例文字颜色
legend1 = ax1.legend(loc='upper left', facecolor='#1A1E43', framealpha=0, edgecolor='white')
legend2 = ax2.legend(loc='upper right', facecolor='#1A1E43', framealpha=0, edgecolor='white')

# 更改图例文字颜色
for text in legend1.get_texts():
    text.set_color("white")
for text in legend2.get_texts():
    text.set_color("white")

# 显示图表
plt.show()
